package br.com.main.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DeckPanel;
import com.google.gwt.user.client.ui.TextBox;

public class CrudUsuarioPresent {

	private Display display;
	private DeckPanel deck;

	interface Display {
		Button getBtCadastrar();

		Button getBtCancelar();

		TextBox getTbNome();

		void cleanCampos();

		String[] getCampos();

		TextBox getTbCep();

		void doGet(String cep);
	}

	public CrudUsuarioPresent(Display tela, DeckPanel deck) {
		this.display = tela;
		this.deck = deck;
		bind();
	}

	private void bind() {
		display.getTbCep().addChangeHandler(new ChangeHandler() {

			@Override
			public void onChange(ChangeEvent event) {
				display.doGet(display.getTbCep().getText());

			}
		});

		display.getBtCadastrar().addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				getServico().cadastroSindicoCondominio(display.getCampos()[0],
						display.getCampos()[1], display.getCampos()[2],
						display.getCampos()[3], display.getCampos()[4],
						display.getCampos()[5], display.getCampos()[6],
						display.getCampos()[7], display.getCampos()[8],
						display.getCampos()[9], display.getCampos()[10],
						display.getCampos()[11], display.getCampos()[12],
						display.getCampos()[13],
						Integer.parseInt(display.getCampos()[14]),
						display.getCampos()[15], new AsyncCallback<String>() {

							@Override
							public void onSuccess(String retorno) {
								if (retorno.equals("Cadastrado")) {
									new DialogBoxCadastro(deck).show();
									display.cleanCampos();
								} else {
									System.out
											.println("Algum campo inv�lido");
								}
							}

							@Override
							public void onFailure(Throwable arg0) {
								// TODO Auto-generated method stub

							}
						});
			}
		});

		display.getBtCancelar().addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				deck.showWidget(0);
				display.cleanCampos();
			}
		});

		display.getTbNome().addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				if (display.getTbNome().getText().equals("Ex: Geyson Daniel")) {
					display.getTbNome().setText("");
				}
			}
		});

	}

	private ComunServicoAsync getServico() {
		return GWT.create(ComunServico.class);
	}

}
